<script setup lang="ts">
  import { ref } from 'vue'
  import type { FeaturedPost } from '@/types/blog'

  // 组件属性定义
  interface Props {
    posts: FeaturedPost[] // 精选文章列表
    loading: boolean // 加载状态
  }

  const props = defineProps<Props>()

  // 组件事件定义
  const emit = defineEmits<{
    'post-click': [postId: string] // 文章点击事件
  }>()

  // 当前轮播索引
  const currentIndex = ref(0)

  // 切换到下一张幻灯片
  const nextSlide = () => {
    if (props.posts.length > 0) {
      // 使用模运算实现循环轮播
      currentIndex.value = (currentIndex.value + 1) % props.posts.length
    }
  }

  // 切换到上一张幻灯片
  const prevSlide = () => {
    if (props.posts.length > 0) {
      // 如果是第一张，则跳转到最后一张
      currentIndex.value =
        currentIndex.value === 0 ? props.posts.length - 1 : currentIndex.value - 1
    }
  }

  // 直接跳转到指定索引的幻灯片
  const goToSlide = (index: number) => {
    currentIndex.value = index
  }

  // 处理文章点击事件
  const handlePostClick = (postId: string) => {
    emit('post-click', postId)
  }

  // 处理图片加载错误
  const handleImageError = (event: Event) => {
    const img = event.target as HTMLImageElement
    // 使用默认占位图
    img.src = 'https://picsum.photos/800/400?random=' + Math.random()
  }

  // ===== 自动轮播功能 =====
  // 自动轮播定时器
  let autoplayTimer: number | null = null

  // 开始自动轮播
  const startAutoplay = () => {
    if (autoplayTimer) clearInterval(autoplayTimer)
    // 每5秒自动切换到下一张
    autoplayTimer = setInterval(nextSlide, 5000)
  }

  // 停止自动轮播
  const stopAutoplay = () => {
    if (autoplayTimer) {
      clearInterval(autoplayTimer)
      autoplayTimer = null
    }
  }

  // 生命周期钩子
  import { onMounted, onUnmounted, watch } from 'vue'

  // 监听posts变化
  watch(
    () => props.posts,
    newPosts => {
      if (newPosts.length > 0 && !autoplayTimer) {
        startAutoplay()
      }
    },
    { deep: true }
  )

  // 组件挂载时开始自动轮播
  onMounted(() => {
    // 只有在有文章时才开始自动轮播
    if (props.posts.length > 0) {
      startAutoplay()
    }
  })

  // 组件卸载时清理定时器
  onUnmounted(() => {
    stopAutoplay()
  })
</script>

<template>
  <!-- 精选文章轮播组件
       功能：展示精选文章的轮播效果
       交互：鼠标悬停时暂停自动播放，移开后恢复
  -->
  <div class="featured-posts" @mouseenter="stopAutoplay" @mouseleave="startAutoplay">
    <!-- 加载状态：显示骨架屏 -->
    <div v-if="loading" class="loading-skeleton">
      <!-- 显示3个骨架卡片 -->
      <div v-for="i in 3" :key="i" class="skeleton-card">
        <div class="skeleton-image"></div>
        <div class="skeleton-content">
          <div class="skeleton-title"></div>
          <div class="skeleton-summary"></div>
          <div class="skeleton-meta"></div>
        </div>
      </div>
    </div>

    <!-- 空状态：没有文章时显示 -->
    <div v-else-if="posts.length === 0" class="empty-state">
      <div class="empty-icon">📝</div>
      <p>暂无精选文章</p>
    </div>

    <!-- 轮播主体 -->
    <div v-else class="carousel-container">
      <div class="carousel-wrapper">
        <!-- 轮播轨道：通过 transform 实现滑动效果 -->
        <div class="carousel-track" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
          <!-- 遍历每篇文章，创建轮播项 -->
          <div v-for="post in posts" :key="post.id" class="carousel-slide">
            <!-- 文章卡片：卡片重叠式设计 -->
            <article class="featured-card" @click="handlePostClick(post.id)">
              <!-- 背景图片 -->
              <div class="card-background">
                <img
                  :src="post.coverImage"
                  :alt="post.title"
                  loading="lazy"
                  @error="handleImageError"
                />
                <!-- 渐变遮罩 -->
                <div class="gradient-overlay"></div>
              </div>

              <!-- 内容覆盖层 -->
              <div class="card-overlay">
                <!-- 顶部：分类标签 -->
                <div class="card-header">
                  <div class="category-badge">{{ post.category }}</div>
                  <div class="meta-icons">
                    <span class="icon-item">👁 {{ post.views }}</span>
                    <span class="icon-item">❤️ {{ post.likes }}</span>
                  </div>
                </div>

                <!-- 底部：文章信息 -->
                <div class="card-body">
                  <!-- 文章标题 -->
                  <h3 class="card-title">{{ post.title }}</h3>

                  <!-- 文章摘要 -->
                  <p class="card-summary">{{ post.summary }}</p>

                  <!-- 底部元信息 -->
                  <div class="card-footer">
                    <div class="meta-info">
                      <span class="author">
                        {{ new Date(post.publishDate).toLocaleDateString('zh-CN') }}
                      </span>
                      <span class="divider">·</span>
                      <span class="read-time">{{ post.readTime }}</span>
                    </div>
                    <div class="read-more">阅读更多 →</div>
                  </div>
                </div>
              </div>
            </article>
          </div>
        </div>
      </div>

      <!-- 导航按钮：只在有多个文章时显示 -->
      <!-- 上一张按钮 -->
      <button
        v-if="posts.length > 1"
        class="nav-button prev-button"
        :disabled="posts.length <= 1"
        @click="prevSlide"
      >
        ‹
      </button>
      <!-- 下一张按钮 -->
      <button
        v-if="posts.length > 1"
        class="nav-button next-button"
        :disabled="posts.length <= 1"
        @click="nextSlide"
      >
        ›
      </button>

      <!-- 轮播指示器：显示当前位置，可点击切换 -->
      <div v-if="posts.length > 1" class="carousel-indicators">
        <button
          v-for="(_post, index) in posts"
          :key="index"
          class="indicator"
          :class="{ active: index === currentIndex }"
          @click="goToSlide(index)"
        ></button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  /* ===== 组件根容器 ===== */
  .featured-posts {
    position: relative;
    width: 100%;
  }

  /* ===== 加载状态样式 ===== */
  /* 骨架屏布局：自适应网格 */
  .loading-skeleton {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
  }

  .skeleton-card {
    background: var(--bg-color);
    border-radius: var(--radius-xl);
    overflow: hidden;
    box-shadow: var(--shadow-md);
  }

  .skeleton-image {
    height: 200px;
    background: linear-gradient(
      90deg,
      var(--bg-secondary) 25%,
      var(--bg-tertiary) 50%,
      var(--bg-secondary) 75%
    );
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
  }

  .skeleton-content {
    padding: 1.5rem;
  }

  .skeleton-title,
  .skeleton-summary,
  .skeleton-meta {
    height: 1rem;
    background: linear-gradient(
      90deg,
      var(--bg-secondary) 25%,
      var(--bg-tertiary) 50%,
      var(--bg-secondary) 75%
    );
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
    border-radius: var(--radius-sm);
    margin-bottom: 0.75rem;
  }

  .skeleton-title {
    height: 1.5rem;
    width: 80%;
  }

  .skeleton-summary {
    width: 100%;
  }

  .skeleton-meta {
    width: 60%;
    margin-bottom: 0;
  }

  @keyframes shimmer {
    0% {
      background-position: -200% 0;
    }
    100% {
      background-position: 200% 0;
    }
  }

  /* ===== 空状态样式 ===== */
  .empty-state {
    text-align: center;
    padding: 3rem;
    color: var(--text-secondary);

    .empty-icon {
      font-size: 3rem;
      margin-bottom: 1rem;
    }

    p {
      font-size: 1.1rem;
      margin: 0;
    }
  }

  /* ===== 轮播容器样式 ===== */
  /* 主容器：包含所有轮播内容 */
  .carousel-container {
    position: relative;
    border-radius: var(--radius-xl);
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    background: var(--bg-secondary);
  }

  .carousel-wrapper {
    width: 100%; // 确保包装器宽度为100%
    overflow: hidden;
    border-radius: var(--radius-xl);
    position: relative; // 为子元素提供定位上下文
  }

  .carousel-track {
    display: flex;
    transition: transform 0.5s ease;
    width: 100%; // 确保轨道宽度
  }

  .carousel-slide {
    width: 100%; // 使用固定宽度而不是最小宽度
    flex-shrink: 0;
    overflow: hidden; // 防止内容溢出
  }

  /* ===== 文章卡片样式 ===== */
  /* 卡片重叠式设计 */
  .featured-card {
    position: relative;
    cursor: pointer;
    height: 500px;
    width: 100%;
    overflow: hidden;
    border-radius: var(--radius-xl);
    transition: all 0.3s ease;

    // 悬停效果
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);

      .card-background img {
        transform: scale(1.05);
      }

      .gradient-overlay {
        opacity: 0.7;
      }

      .read-more {
        transform: translateX(4px);
      }
    }
  }

  // 背景图片容器
  .card-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.6s ease;
    }
  }

  // 渐变遮罩
  .gradient-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(0, 0, 0, 0.1) 30%,
      rgba(0, 0, 0, 0.8) 100%
    );
    opacity: 0.6;
    transition: opacity 0.3s ease;
  }

  // 内容覆盖层
  .card-overlay {
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 2rem;
    color: white;
    z-index: 1;
  }

  // 顶部区域
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .meta-icons {
    display: flex;
    gap: 1rem;

    .icon-item {
      background: rgba(0, 0, 0, 0.5);
      padding: 0.25rem 0.75rem;
      border-radius: var(--radius-lg);
      font-size: 0.85rem;
      backdrop-filter: blur(10px);
    }
  }

  // 底部内容区域
  .card-body {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .category-badge {
    background: rgba(255, 255, 255, 0.2);
    color: white;
    padding: 0.375rem 1rem;
    border-radius: var(--radius-lg);
    font-size: 0.85rem;
    font-weight: 600;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
  }

  .card-title {
    font-size: 2rem;
    font-weight: 700;
    color: white;
    margin: 0;
    line-height: 1.2;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .card-summary {
    color: rgba(255, 255, 255, 0.9);
    line-height: 1.5;
    margin: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    font-size: 1rem;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 1rem;
  }

  .meta-info {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.9rem;
    color: rgba(255, 255, 255, 0.8);

    .divider {
      opacity: 0.6;
    }
  }

  .read-more {
    color: white;
    font-weight: 600;
    font-size: 0.95rem;
    transition: transform 0.3s ease;
    cursor: pointer;
  }

  /* ===== 导航控制样式 ===== */
  /* 导航按钮：左右切换按钮 */
  .nav-button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%); // 垂直居中
    width: 48px;
    height: 48px;
    border: none;
    border-radius: 50%; // 圆形按钮
    background: rgba(255, 255, 255, 0.9);
    color: var(--text-primary);
    font-size: 1.5rem;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s ease;
    z-index: 10; // 确保在内容之上
    box-shadow: var(--shadow-md);

    // 悬停效果：放大
    &:hover {
      background: white;
      transform: translateY(-50%) scale(1.1);
    }

    // 禁用状态
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }

  .prev-button {
    left: 1rem;
  }

  .next-button {
    right: 1rem;
  }

  /* 指示器 */
  .carousel-indicators {
    position: absolute;
    bottom: 1rem;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 0.5rem;
    z-index: 10;
  }

  .indicator {
    width: 12px;
    height: 12px;
    border: none;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.5);
    cursor: pointer;
    transition: all 0.3s ease;

    &.active {
      background: var(--primary-color);
      transform: scale(1.2);
    }

    &:hover {
      background: rgba(255, 255, 255, 0.8);
    }
  }

  /* ===== 响应式设计 ===== */
  /* 平板设备 (768px以下) */
  @media (max-width: 768px) {
    // 调整卡片高度
    .featured-card {
      height: 400px;
    }

    // 调整内容间距
    .card-overlay {
      padding: 1.5rem;
    }

    // 调整标题大小
    .card-title {
      font-size: 1.5rem;
    }

    // 调整摘要文字
    .card-summary {
      font-size: 0.9rem;
      -webkit-line-clamp: 2;
      line-clamp: 2;
    }

    // 缩小导航按钮
    .nav-button {
      width: 40px;
      height: 40px;
      font-size: 1.2rem;
    }

    // 调整按钮位置
    .prev-button {
      left: 0.5rem;
    }

    .next-button {
      right: 0.5rem;
    }
  }

  /* 手机设备 (480px以下) */
  @media (max-width: 480px) {
    // 调整卡片高度
    .featured-card {
      height: 350px;
    }

    // 调整内容间距
    .card-overlay {
      padding: 1rem;
    }

    // 调整标题大小
    .card-title {
      font-size: 1.25rem;
    }

    // 隐藏摘要以节省空间
    .card-summary {
      display: none;
    }

    // 调整元信息字体
    .meta-info {
      font-size: 0.8rem;
    }

    .read-more {
      font-size: 0.85rem;
    }
  }
</style>
